package org.loofer.baseframe;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Response;
import android.app.Dialog;
import android.content.Context;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.Toast;

import com.example.okhttp.utils.OKHttpUICallback;
import com.example.okhttp.utils.OkHttpManger;
/**
 * Created by Seeker on 2016/7/29.
 */

public class ProgressBarDialog extends Dialog implements OKHttpUICallback.ProgressCallback{

    private static final String TAG = "ProgressBarDialog";


    ProgressBar progressBar;

    private String url;

    public ProgressBarDialog(Context context, int themeResId) {
        super(context, themeResId);
    }

    protected ProgressBarDialog(Context context, boolean cancelable, OnCancelListener cancelListener) {
        super(context, cancelable, cancelListener);
    }

    public ProgressBarDialog(Context context,String url) {
        super(context);
        this.url = url;
        setContentView(R.layout.progress_layout);
    }

    @Override
    public void setContentView(int layoutResID) {
        super.setContentView(layoutResID);
        progressBar = (ProgressBar) findViewById(R.id.progressbar);
        
        /**
         * public void downloadAsync(final String url, final String destFileDir,final OKHttpUICallback.ProgressCallback downListener) 
         */
        
        final String absolutePath = Config.getDirFile("download").getAbsolutePath();
        
        findViewById(R.id.load).setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				
				try {
					OkHttpManger.getInstance().downloadAsync(url, absolutePath, ProgressBarDialog.this);
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		});
    }

    @Override
    public void cancel() {
        super.cancel();
    }


    @Override
    public void onSuccess(Call call, Response response,String path) {
        Toast.makeText(getContext(),"download finish!path = "+path,Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onProgress(long byteReadOrWrite, long contentLength, boolean done) {
        progressBar.setProgress((int)(byteReadOrWrite / contentLength *100));
    }

    @Override
    public void onError(Call call, IOException e) {
        Toast.makeText(getContext(),"download error!",Toast.LENGTH_SHORT).show();
    }
}
